package com.framework.disconf.config;

import com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

import java.io.IOException;

public class DisconfPropertiesSpringInit implements BeanFactoryPostProcessor {

    private static final Logger log = LoggerFactory.getLogger(DisconfPropertiesSpringInit.class);
    private static final String DISCONF_PROPERTY_SOURCE_NAME = "DisConfPropertySources";
    private ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean;
    private ConfigurableEnvironment environment;

    DisconfPropertiesSpringInit(ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean, ConfigurableEnvironment environment) {
        this.reloadablePropertiesFactoryBean = reloadablePropertiesFactoryBean;
        this.environment = environment;
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if (!this.environment.getPropertySources().contains(DISCONF_PROPERTY_SOURCE_NAME)) {
            CompositePropertySource composite = new CompositePropertySource(DISCONF_PROPERTY_SOURCE_NAME);

            try {
                composite.addPropertySource(new PropertiesPropertySource(DISCONF_PROPERTY_SOURCE_NAME, this.reloadablePropertiesFactoryBean.getObject()));
            } catch (IOException var4) {
                log.error(var4.getMessage(), var4);
            }

            this.environment.getPropertySources().addFirst(composite);
        }
    }

}
